﻿using JavaDevToys.Rcl.Service;
using OneOf.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage.Pickers;

[assembly: Dependency(typeof(JavaDevToys.Rcl.Service.IDirectoryPicker))]
namespace JavaDevToys.Platforms.Windows.Service.Impl
{
    public class DirectoryPicker: IDirectoryPicker
    {
        private bool found=false;

        List<string> IDirectoryPicker.GetFolderDirectories(string currentPath)
        {
            return Directory.GetDirectories(currentPath).ToList();
        }

        async Task<string> IDirectoryPicker.PickDirectoryAsync()
        {
            var picker = new FolderPicker();
            picker.SuggestedStartLocation = PickerLocationId.Desktop;
            picker.FileTypeFilter.Add("*");

            // 获取窗口句柄
            var window = Application.Current.Windows[0].Handler.PlatformView as MauiWinUIWindow;
            WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(window));

            var folder = await picker.PickSingleFolderAsync();
            return folder?.Path;
        }

        public List<string> SearchAllDirectory(string currentPath, string targetFolderName)
        {
            List<string> result = new List<string>();
            try
            {
                // 获取当前目录下的所有子目录
                string[] subDirectories = Directory.GetDirectories(currentPath);

                foreach (var dir in subDirectories)
                {
                    // 获取文件夹名称
                    string folderName = Path.GetFileName(dir);
                    if(folderName == "target"|| folderName=="resources")
                        continue;
                    var parentFolderName = Directory.GetParent(dir).Name;
                    // 检查是否为目标文件夹
                    if (folderName.Equals(targetFolderName, StringComparison.Ordinal))
                    {
                        result.Add(dir);
                    }

                    // 递归搜索子目录
                    var path = SearchAllDirectory(dir, targetFolderName);
                    if (path.Count > 0) {
                        result.AddRange(path);
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                // 忽略无权限访问的目录
                throw new Exception("无权限访问的目录"+ex.Message);
            }
            catch (PathTooLongException ex)
            {
                // 忽略路径过长的目录
                throw new Exception("路径过长" + ex.Message);
            }
            return result;
        }

        string IDirectoryPicker.SearchDirectory(string currentPath, string targetFolderName, string baseFolderName = null)
        {
            found = false;
            string result = SearchDirectory(currentPath, targetFolderName, baseFolderName);
            if (!result.Contains(targetFolderName))
                throw new Exception($"未找到文件夹【{targetFolderName}】,请先建立项目目录");
            return result;
        }

        private string SearchDirectory(string currentPath, string targetFolderName, string baseFolderName = null)
        {
            if (found)
                return currentPath; // 如果已经找到，停止进一步搜索
            try
            {
                // 获取当前目录下的所有子目录
                string[] subDirectories = Directory.GetDirectories(currentPath);

                foreach (var dir in subDirectories)
                {
                    // 获取文件夹名称
                    string folderName = Path.GetFileName(dir);
                    if (folderName == "target" || (folderName == "resources" && baseFolderName != "resources"))
                        continue;
                    var parentFolderName = Directory.GetParent(dir).Name;
                    // 检查是否为目标文件夹
                    if (folderName.Equals(targetFolderName, StringComparison.Ordinal)&&(parentFolderName==baseFolderName||baseFolderName==null))
                    {
                        Console.WriteLine($"找到目标文件夹: {dir}");
                        found = true;
                        return dir; // 找到后停止搜索
                    }

                    // 递归搜索子目录
                    var path=SearchDirectory(dir, targetFolderName, baseFolderName);

                    if (found)
                        return path; // 如果在子目录中找到了，停止搜索
                }
            }
            catch (UnauthorizedAccessException)
            {
                // 忽略无权限访问的目录
                return currentPath;
            }
            catch (PathTooLongException)
            {
                // 忽略路径过长的目录
                return currentPath;
            }
            return currentPath;
        }

        public bool SearchFile(string currentPath, string fileName, out string fileFullName)
        {
            try
            {
                // 获取当前目录下的所有文件
                var files = Directory.GetFiles(currentPath);
                foreach (var file in files)
                {
                    if (Path.GetFileName(file) == fileName)
                    {
                        fileFullName = file;
                        return true;
                    }
                }

                // 获取当前目录下的所有子目录
                string[] subDirectories = Directory.GetDirectories(currentPath);

                foreach (var dir in subDirectories)
                {
                    string folderName = Path.GetFileName(dir);
                    if (folderName == "target" || folderName == "resources")
                        continue;
                    // 递归调用，继续在子目录中查找
                    if (SearchFile(dir, fileName, out fileFullName))
                    {
                        return true; // 如果在子目录中找到文件，则立即返回
                    }
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                // 忽略无权限访问的目录
                throw new Exception("无权限访问的目录" + ex.Message);
            }
            catch (PathTooLongException ex)
            {
                // 忽略路径过长的目录
                throw new Exception("路径过长" + ex.Message);
            }

            // 如果未找到文件
            fileFullName = string.Empty;
            return false;
        }
    }
}
